package com.smart.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

/*
 * by:HH
 * Json转换工具
 * */
public class JsonHelper {

/*
 * JavaBean转Map
 * @param javabean
 * 			javabean
 * 
 * */
	public static Map toMap(Object javabean){
		Map result = new HashMap();
		Method[] methods = javabean.getClass().getDeclaredMethods();
		
		for(Method method :methods){
			
			if(method.getName().startsWith("get")){
				String field = method.getName();
				field = field.substring(field.indexOf("get")+3);
				try {
					Object value = method.invoke(javabean, null);
					result.put(field,value == null? "":value.toString());
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
		return result;
	}
	
	/*
	 * by:HH
	 * 
	 * 将JavaBean转JsonObject
	 * 
	 * @param:javabean
	 * 			javabean
	 * 
	 * */
	public static JSONObject toJson(Object javabean){
		return new JSONObject(toMap(javabean));
	}
}
